package com.lambkit.config;

import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.lambkit.core.config.ConfigCenter;
import com.lambkit.service.JFResourceFactory;

import java.io.File;
import java.util.*;

/**
 * 用于读取本地配置信息
 */
public class PropConfigCenter implements ConfigCenter {

    private Prop prop;
    private String name;

    public PropConfigCenter(String name) {
    	this.name = name;
    	if(StrKit.isBlank(this.name)) {
    		this.name = "lambkit";
    	}
        String pname = this.name.indexOf(".") > 0 ? this.name : this.name + ".properties";
        prop = readProp(pname);
        initModeProp(prop);
    }
    
    @Override
    public String getName() {
    	// TODO Auto-generated method stub
    	return name;
    }
    
	@Override
	public String getValue(String key) {
		// TODO Auto-generated method stub
		return prop.get(key);
	}

	@Override
	public boolean containsKey(String key) {
		// TODO Auto-generated method stub
		return prop.containsKey(key);
	}

	@Override
	public boolean refresh() {
		// TODO Auto-generated method stub
		refreshModeProp(prop);
		return true;
	}

    @Override
    public void setValue(String name, String key, String value) {
        if(this.name.equals(name)) {
            prop.getProperties().setProperty(key, value);
        }
	}
	
	@Override
	public void removeValue(String key) {
		// TODO Auto-generated method stub
		prop.getProperties().remove(key);
	}

    public List<String> getKeys(String prefix) {
        List<String> keyList = new ArrayList<String>();
        Properties properties = prop.getProperties();
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            String key = entry.getKey().toString();
            if (key.startsWith(prefix) && entry.getValue() != null) {
                keyList.add(key);
            }
        }
        return keyList;
    }

	public List<String> getKeys() {
		// TODO Auto-generated method stub
    	Enumeration<Object> keys = prop.getProperties().keys();
		List<String> keyList = new ArrayList<String>();
		while (keys.hasMoreElements()) {
			String key = keys.nextElement().toString();
			keyList.add(key);
		}
		return keyList;
	}

    /**
     * 或者默认的配置信息
     * GatewayManager、NodeManager在使用
     * @return
     */
    public Properties getProperties() {
        Properties properties = new Properties();
        properties.putAll(prop.getProperties());
        return properties;
    }


    /**
     * 初始化不同model下的properties文件
     *
     * @param prop
     */
    private void initModeProp(Prop prop) {
        String mode = prop.get("lambkit.mode");
        if (StrKit.isBlank(mode)) {
            return;
        }

        Prop modeProp = null;
        try {
            String p = String.format(this.name + "-%s.properties", mode);
            modeProp = readProp(p);
        } catch (Throwable ex) {
        }

        if (modeProp == null) {
            return;
        }

        prop.getProperties().putAll(modeProp.getProperties());
    }

    private Prop readProp(String propName) {
        Prop theProp = null;
        JFResourceFactory resourceFactory = new JFResourceFactory();
        String rootPath = resourceFactory.getResourceService().getRootPath();
        //优先查找config下有没有properties
        String fileName = rootPath + File.separator + "config" + File.separator + propName;
        File file = new File(fileName);
        if(file.exists()) {
            theProp = PropKit.use(file);
        } else {
            //优先查找root下有没有properties
            fileName = rootPath + File.separator + propName;
            if(file.exists()) {
                theProp = PropKit.use(file);
            } else {
                theProp = PropKit.use(propName);
            }
        }
        if(theProp==null) {
            theProp = new Prop();
        }
        return theProp;
    }
    
    /**
     * 初始化不同model下的properties文件
     *
     * @param prop
     */
    private void refreshModeProp(Prop prop) {
        String mode = PropKit.use("lambkit.properties").get("lambkit.mode");
        if (StrKit.isBlank(mode)) {
            return;
        }

        Prop modeProp = null;
        try {
            String p = String.format("lambkit-%s.properties", mode);
            modeProp = PropKit.use(p);
        } catch (Throwable ex) {
        }

        if (modeProp == null) {
            return;
        }

        prop.getProperties().clear();
        prop.getProperties().putAll(modeProp.getProperties());
    }
    
    public Prop getProp() {
		return prop;
	}
}
